<!--
使用antd原生Form生成 详细用法参考ant-design-vue Form组件文档
vscode默认配置文件会自动格式化/移除未使用依赖
-->
<script setup lang="ts">
import type { RuleObject } from 'ant-design-vue/es/form';
import { computed, ref, watch } from 'vue';

import {
  Input,
  Textarea,
  Select,
  RadioGroup,
  CheckboxGroup,
  DatePicker,
  Form,
  FormItem,
  Row,
  Col,
  InputNumber,
  Button,
  Space,
  message
} from 'ant-design-vue';
import { confirm, prompt } from '@vben/common-ui';
import { ImageUpload, FileUpload } from '#/components/upload';
import { Tinymce } from '#/components/tinymce';
import { getPopupContainer } from '@vben/utils';
import { pick } from 'lodash-es';

import { getDictOptions } from '#/utils/dict';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import {
  purchaseContractAdd,
  purchaseContractInfo,
  purchaseContractUpdate,
  purchaseInfo,
  purchaseContractSubmit,
  purchaseContractApprove,
  purchaseContractReject,
  purchaseContractInvalidate,
} from '#/api/trade/purchaseContract';
import type { PurchaseContractForm } from '#/api/trade/purchaseContract/model';
import { customerList, customerInfo } from '#/api/trade/customer';
import { userList } from '#/api/system/user';
import { useBeforeCloseDiff } from '#/utils/popup';
import type { IDS, ID } from '#/api/common';
import type { DefaultOptionType, SelectValue } from 'ant-design-vue/es/select';
import type { SaleContractDetailVO } from '#/api/trade/saleContract/model';
import SaleContractDetails from '../saleContract/components/SaleContractDetails.vue';
import { APPROVE_STATUS } from '../constants';

const emit = defineEmits<{ reload: [] }>();
APPROVE_STATUS
// 采购合同状态定义
const CONTRACT_STATUS = {
 ... APPROVE_STATUS,
  SHIPPED: 'shipped', // 已发货
};

const isUpdate = ref(false);

// 当前合同状态
const currentStatus = computed(() => formData.value.status || CONTRACT_STATUS.DRAFT);

 

// 驳回原因是否可见
const showRejectReason = computed(() => {
  return formData.value.rejectReason && formData.value.rejectReason.trim() !== '';
});

// 客户列表数据
const customerOptions = ref<{ label: string; value: string | number }[]>([]);
const customerLoading = ref(false);

// 销售人员列表数据
const saleUserOptions = ref<{ label: string; value: string | number }[]>([]);
const saleUserLoading = ref(false);

// 加载客户列表
const loadCustomerOptions = async (keyword?: string) => {
  customerLoading.value = true;
  try {
    const { rows } = await customerList({
      pageNum: 1,
      pageSize: 200,
      name: keyword, // 使用name字段作为搜索条件
    });
    customerOptions.value = rows.map((item) => ({
      label: item.name,
      value: item.id,
    }));
  } finally {
    customerLoading.value = false;
  }
};

// 初始加载客户列表
loadCustomerOptions();

// 加载销售人员列表
const loadSaleUserOptions = async () => {
  saleUserLoading.value = true;
  try {
    const { rows } = await userList({
      pageNum: 1,
      pageSize: 200,
    });
    saleUserOptions.value = rows.map((item) => ({
      label: item.nickName,
      value: item.userId,
    }));
  } finally {
    saleUserLoading.value = false;
  }
};

// 初始加载销售人员列表
loadSaleUserOptions();

/**
 * 定义默认值 用于reset
 */
const defaultValues: Partial<PurchaseContractForm> = {
  id: undefined,
  deptId: undefined,
  contractNo: undefined,
  contractDate: new Date().toISOString().slice(0, 19).replace('T', ' '),
  supplierId: undefined,
  contact: undefined,
  contactPhone: undefined,
  purchaseUserid: undefined,
  currency: undefined,
  totalAmount: undefined,
  contractPic: undefined,
  logisticsPic: undefined,
  status: 'draft',
  approverId: undefined,
  approveTime: undefined,
  rejectReason: undefined,
  details: [],
  remark: undefined,
};

/**
 * 表单数据ref
 */
const formData = ref(defaultValues);

type AntdFormRules<T> = Partial<Record<keyof T, RuleObject[]>> & {
  [key: string]: RuleObject[];
};
/**
 * 表单校验规则
 */
const formRules = ref<AntdFormRules<PurchaseContractForm>>({
  contractDate: [{ required: true, message: '合同日期不能为空' }],
  supplierId: [{ required: true, message: '供应商不能为空' }],
  contact: [{ required: true, message: '联系人不能为空' }],
  contactPhone: [{ required: true, message: '联系方式不能为空' }],
  purchaseUserid: [{ required: true, message: '采购人不能为空' }],
  currency: [{ required: true, message: '币种不能为空' }],
});

/**
 * useForm解构出表单方法
 */
const { validate, validateInfos, resetFields } = Form.useForm(
  formData,
  formRules,
);

function customFormValueGetter() {
  return JSON.stringify(formData.value);
}

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: customFormValueGetter,
    currentGetter: customFormValueGetter,
  },
);

// 监听客户选择变化，自动填充联系人、联系方式和销售信息
const handleCustomerChange = async (value: SelectValue) => {
  if (!value) return;

  try {
    const customerData = await customerInfo(value as ID);
    if (customerData) {
      // 自动填充联系人、联系方式和销售信息
      formData.value.contact = customerData.contact;
      formData.value.contactPhone = customerData.contactPhone;
    }
  } catch (error) {
    console.error('获取客户详情失败', error);
  }
};
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

// 将采购合同明细转换为销售合同明细格式，用于SaleContractDetails组件
const saleContractDetails = computed({
  get(): SaleContractDetailVO[] {
    if (!formData.value.details) return [];
    return formData.value.details.map((detail) => ({
      id: detail.order?.saleContractDetailId || detail.id || '',
      brandId: detail.order?.saleContract?.details?.[0]?.brandId || '',
      spuId: detail.order?.saleContract?.details?.[0]?.spuId || '',
      skuId: detail.order?.saleContract?.details?.[0]?.skuId || '',
      others: detail.order?.saleContract?.details?.[0]?.others || '',
      amount: detail.order?.saleContract?.details?.[0]?.amount || 0,
      frameNo: detail.order?.frameNo || '',
      purchaseAmount: detail.purchaseAmount || 0,
      orderNo: detail.order?.orderNo || '',
      customerName: detail.order?.saleContract?.customerName
    }));
  },
  set(value: SaleContractDetailVO[]) {
    // 当SaleContractDetails组件更新数据时，同步更新formData.details
    if (!formData.value.details) formData.value.details = [];

    // 更新purchaseAmount字段
    value.forEach((saleDetail, index) => {
      if (formData.value.details![index]) {
        formData.value.details![index].purchaseAmount = saleDetail.purchaseAmount || 0;
        formData.value.details![index].order!.frameNo = saleDetail.frameNo;
      }
    });
    formData.value.totalAmount = value.reduce(
      (sum, detail) => sum + (detail.purchaseAmount || 0),
      0,
    );

  },
});

// // 计算合同总价：saleContractDetails集合中所有amount的总和
// const totalAmount = computed(() => {
//   return saleContractDetails.value.reduce(
//     (sum, detail) => sum + (detail.purchaseAmount || 0),
//     0,
//   );
// });

// // 监听totalAmount变化，自动更新formData.totalAmount
// watch(
//   totalAmount,
//   (newValue) => {
//     formData.value.totalAmount = newValue;
//   },
//   { immediate: true },
// );

const [BasicDrawer, drawerApi] = useVbenDrawer({
  class: 'w-[900px]',
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  showConfirmButton: false, // 隐藏默认确认按钮，使用自定义按钮
  showCancelButton: false,  // 隐藏默认取消按钮
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    drawerApi.drawerLoading(true);

    const { id, orderIds } = drawerApi.getData() as {
      id?: number | string;
      orderIds?: IDS;
    };
    isUpdate.value = !!id;
    if (isUpdate.value && id) {
      const record = await purchaseContractInfo(id);
      // 只赋值存在的字段
      const filterRecord = pick(record, Object.keys(defaultValues));
      formData.value = filterRecord;
    } else {
      //订单列表生成采购合同
      const record = await purchaseInfo(orderIds!);
      // 只赋值存在的字段
      const filterRecord = pick(record, Object.keys(defaultValues));
      formData.value = filterRecord;
      // console.log('saleContractDetails',saleContractDetails.value)
      console.log('purchaseInfo', record);
    }
    await markInitialized();

    drawerApi.drawerLoading(false);
  },
});

async function handleConfirm() {
  try {
    drawerApi.lock(true);
    await validate();
    // 可能会做数据处理 使用cloneDeep深拷贝
    const data = cloneDeep(formData.value);
    
    // 如果合同号为空，自动生成
    if (!data.contractNo || data.contractNo.trim() === '') {
      data.contractNo = generateContractNo();
    }
    if(!data.status){
      data.status = CONTRACT_STATUS.DRAFT;
    }
    await (isUpdate.value ? purchaseContractUpdate(data) : purchaseContractAdd(data));
    resetInitialized();
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    drawerApi.lock(false);
  }
}

async function handleClosed() {
  formData.value = defaultValues;
  resetFields();
  resetInitialized();
}

// 生成合同号的函数
const generateContractNo = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  const milliseconds = String(now.getMilliseconds()).padStart(3, '0');
  
  return `${year}${month}${day}${hours}${minutes}${seconds}${milliseconds}`;
};

// 作废合同
const handleInvalidate = async () => {
  try {
    await confirm({
      title: '确认作废',
      content: '确定要作废该合同吗？作废后无法恢复。',
    });
    
    await purchaseContractInvalidate({id:formData.value.id!});
    message.success('作废成功');
    emit('reload');
    drawerApi.close();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('作废失败:', error);
    }
  }
};

// 审核通过
const handleApprove = async () => {
  try {
    await confirm({
      title: '确认通过',
      content: '确定要通过该合同吗？',
    });
    
    await purchaseContractApprove(formData.value.id!);
    message.success('审核通过成功');
    emit('reload');
    drawerApi.close();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核通过失败:', error);
    }
  }
};

// 驳回合同
const handleReject = async () => {
  try {
    const reason = await prompt<string>({
      title: '驳回合同',
      content: '请输入驳回原因：',
      componentProps: {
        placeholder: '请输入驳回原因（不超过200字）',
      },
      beforeClose({ isConfirm, value }) {
        if (!isConfirm) return true;
        if (!value || !value.trim()) {
          message.error('请输入驳回原因');
          return false;
        }
        if (value.trim().length > 200) {
          message.error('驳回原因不能超过200字');
          return false;
        }
        return true;
      },
    });
    
    if (reason && reason.trim()) {
      await purchaseContractReject({ id: formData.value.id!, rejectReason: reason.trim() });
      message.success('驳回成功');
      emit('reload');
      drawerApi.close();
    }
  } catch (error) {
    // 用户取消操作或其他错误
    if (error !== 'cancel') {
      console.error('驳回失败:', error);
    }
  }
};

// 提交审核
const handleSubmitReview = async () => {
  try {
    drawerApi.lock(true);
    await validate();
    
    // 如果合同号为空，自动生成
    if (!formData.value.contractNo || formData.value.contractNo.trim() === '') {
      formData.value.contractNo = generateContractNo();
    }
    
    // 先保存合同信息
    const data = cloneDeep(formData.value);
    await (isUpdate.value ? purchaseContractUpdate(data) : purchaseContractAdd(data));
    
    // 如果是新增，需要获取返回的ID
    if (!isUpdate.value && data.id) {
      formData.value.id = data.id;
    }
    
    // 再提交审核
    await purchaseContractSubmit([formData.value.id!]);
    message.success('提交审核成功');
    resetInitialized();
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error('提交审核失败:', error);
  } finally {
    drawerApi.lock(false);
  }
};

// 提交
const handleSubmit = async () => {
  try {
    drawerApi.lock(true);
    await validate();
    
    // 如果合同号为空，自动生成
    if (!formData.value.contractNo || formData.value.contractNo.trim() === '') {
      formData.value.contractNo = generateContractNo();
    }
    
    // 先更新合同信息
    await purchaseContractUpdate(formData.value);
    // 再提交审核
    await purchaseContractSubmit([formData.value.id!]);
    message.success('重新提交成功');
    resetInitialized();
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error('重新提交失败:', error);
  } finally {
    drawerApi.lock(false);
  }
};
</script>

<template>
  <BasicDrawer :title="title" :width="1000">
    <Form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="合同号" v-bind="validateInfos.contractNo">
            <Input
              v-model:value="formData.contractNo"
              placeholder="请输入合同号，忽略则自动生成"
              :disabled="isUpdate"
            />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="合同日期" v-bind="validateInfos.contractDate">
            <DatePicker
              v-model:value="formData.contractDate"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
              :disabled="isUpdate"
            />
          </FormItem>
        </Col>
      </Row>

      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="供应商" v-bind="validateInfos.supplierId">
            <Select
              v-model:value="formData.supplierId"
              :options="customerOptions"
              :loading="customerLoading"
              show-search
              :filter-option="false"
              :getPopupContainer="getPopupContainer"
              :placeholder="$t('ui.formRules.selectRequired')"
              @search="loadCustomerOptions"
              @change="handleCustomerChange"
              :disabled="isUpdate"
            />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="联系人">
            <Input
              v-model:value="formData.contact"
              :placeholder="$t('ui.formRules.required')"
              disabled
            />
          </FormItem>
        </Col>
      </Row>

      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="联系方式">
            <Input
              v-model:value="formData.contactPhone"
              :placeholder="$t('ui.formRules.required')"
              disabled
            />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="采购人" v-bind="validateInfos.purchaseUserid">
            <Select
              v-model:value="formData.purchaseUserid"
              :options="saleUserOptions"
              :loading="saleUserLoading"
              show-search
              :filter-option="
                (input, option) =>
                  (option?.label ?? '')
                    .toString()
                    .toLowerCase()
                    .includes(input.toLowerCase())
              "
              :getPopupContainer="getPopupContainer"
              :placeholder="$t('ui.formRules.selectRequired')"
              :disabled="isUpdate"
            />
          </FormItem>
        </Col>
      </Row>
      <Row>
        <!-- 销售明细部分 -->
        <Col :span="24">
          <FormItem
            v-bind="validateInfos.details"
            :wrapper-col="{ span: 24 }"
            :label-col="{ span: 0 }"
          >
            <SaleContractDetails
              v-model="saleContractDetails"
              :disabled="true"
              :show-actions="false"
              :show-frame-no="true"
              :frame-no-editable="true"
              :show-purchase-amount="true"
              :purchase-amount-editable="!isUpdate"
            />
          </FormItem>
        </Col>
      </Row>

      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="合同总价" v-bind="validateInfos.totalAmount">
            <InputNumber
              v-model:value="formData.totalAmount"
              placeholder="自动计算"
              :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :precision="3"
              disabled
            />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="币种" v-bind="validateInfos.currency">
            <Select
              v-model:value="formData.currency"
              :options="getDictOptions('currency')"
              :getPopupContainer="getPopupContainer"
              :placeholder="$t('ui.formRules.selectRequired')"
              :disabled="isUpdate"
            />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
          <Col :span="24">
            <FormItem label="备注" :label-col="{ span: 3 }">
              <Textarea
                v-model:value="formData.remark"
                placeholder="请输入备注"
              />
            </FormItem>
          </Col>
        </Row>
      <!-- 图片上传字段单独占一行，因为需要更多空间 -->
      <Row>
        <Col :span="12">
          <FormItem
            label="检测报告"
            v-bind="validateInfos.testReportPic"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
          >
            <FileUpload 
              :max-count="1" 
              v-model:value="formData.contractPic"
              accept=".jpg,.jpeg,.png,.gif,.webp,.xlsx,.csv,.docx,.pdf"
            />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem
            label="物流信息"
            v-bind="validateInfos.logisticsPic"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
          >
            <FileUpload 
              :max-count="1" 
              v-model:value="formData.logisticsPic"
              accept=".jpg,.jpeg,.png,.gif,.webp,.xlsx,.csv,.docx,.pdf"
            />
          </FormItem>
        </Col>
      </Row>
      <!-- 驳回原因字段，仅在有驳回原因时显示 -->
      <Row v-if="showRejectReason">
        <Col :span="24">
          <FormItem
            label="驳回原因"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
          >
            <Textarea
              v-model:value="formData.rejectReason"
              :rows="3"
              placeholder="驳回原因"
              disabled
              :maxlength="200"
              show-count
            />
          </FormItem>
        </Col>
      </Row>
    </Form>
    
    <!-- 自定义操作按钮 -->
    <template #footer>
        <!-- 操作按钮 -->
        <div class="flex space-x-3">
          <Button v-if="formData.status === APPROVE_STATUS.DRAFT || formData.status === APPROVE_STATUS.REJECTED" type="primary" @click="handleSubmit">提交审核</Button>
          <Button v-if="formData.status === APPROVE_STATUS.WAITING" type="primary" @click="handleApprove">通过</Button>
          <Button v-if="formData.status === APPROVE_STATUS.WAITING" danger @click="handleReject">驳回</Button>
          <Button v-if="formData.status === APPROVE_STATUS.DRAFT ||  formData.status === APPROVE_STATUS.REJECTED" danger @click="handleInvalidate">作废</Button>
          <Button  v-if="!formData.status || formData.status === APPROVE_STATUS.DRAFT || formData.status === APPROVE_STATUS.REJECTED || formData.status === APPROVE_STATUS.PASSED" type="primary" @click="handleConfirm">仅保存</Button>
          <Button @click="drawerApi.close()">返回</Button>
        </div>
    </template>
  </BasicDrawer>
</template>
